import React, { Fragment } from 'react'
import {

  Text,
  ScrollView,
  View
} from 'react-native'
import BasePage from 'src/pageP/base/base-page/index'
import CustomButton from 'src/components/button/CustomButton'
import CustomBoxShadow from 'src/components/boxshadow/CustomBoxShadow'
import CustomImage from 'src/components/image/CustomImage'
import {
  getCompanyWorkLocationList,
  insertCompanyWorkLocation,
  deleteCompanyWorkLocation,
  companyRightInfo
} from '@utils/RequestAPI'
import { CommonToast } from 'src/utils/ToastUtil'
import CustomModalAnimatable from '@/components/modal/CustomModalAnimatable'
import CheckDeleteView from 'src/components/check-delete-view/index'
import styles from './css/index'
import { isLegalCity } from 'src/utils/ConfigUtil'
/* redux */
class AddSite extends BasePage {
  constructor(props) {
    super(props)
    this.state = {
      header: {
        headerBg: 'transparent'
      },
      postAddress: 0,
      isDelState: false,
      isChecAll: false,
      visible: false,
      vipModal: false,
      member: false,
      vipModalText: '',
      item: {},
      businessAddress: '',
      addressDetail: '',
      locationList: [],
      isPitchOnList: [],
      WorkLocations: []
    }
  }

  getCompanyWorkLocationList = () => {
    const { navigation: { state: { params: { companyId } } } } = this.props
    getCompanyWorkLocationList({ headers: { companyId } }).then((data) => {
      this.setState({
        locationList: data.data.map((item) => {
          item.locationId = item.id
          item.id = null
          return item
        })
      })
    })
  }

  getcompanyRightInfo = () => {

  }

  componentDidMount() {
    this.getcompanyRightInfo()
    if (this.props.navigation.state.params && this.props.navigation.state.params.isPitchOnList) {
      this.setState({
        isPitchOnList: this.props.navigation.state.params.isPitchOnList
      })
    }
    this.getCompanyWorkLocationList()
  }

  getData = (data, datas, Fn, companyId, item) => {
    const { navigation: { state: { params: { userId } } } } = this.props
    const { cityname, adname, address, name } = item
    if (isLegalCity(cityname.replace(/市/, ''))) {
      if (data.lat) {
        insertCompanyWorkLocation({
          params: {
            createdBy: userId,
            companyId,
            cityName: cityname.replace(/市/, ''),
            areaName: adname,
            address: cityname + adname + address,
            latitude: data.lat,
            longitude: data.lng,
            addressSimple: name,
            roomInfo: data.roomInfo
          }
        }).then((e) => {
          this.setState({
            isPitchOnList: [...this.state.isPitchOnList, { ...datas, areaName: datas.addressArea, latitude: datas.lat, longitude: datas.lng, cityName: datas.areaCity.replace(/市/, ''), locationId: e.data, address: cityname + adname + address }],
            WorkLocations: [...this.state.WorkLocations, item.name]
          })
          this.getCompanyWorkLocationList()
          this.props.navigation.navigate('AddSite')
        })
      } else {
        this.props.navigation.navigate('AddSite')
      }
    } else {
      CommonToast('您选择的地址未在平台服务区域内')
    }
  }

  isPitchOn = ({ item }) => {
    let { isPitchOnList, locationList } = this.state
    const welfareList = (isPitchOnList || [{}]).filter((e) => e.locationId === item.locationId)
    if (welfareList.length > 0) {
      isPitchOnList = (isPitchOnList || [{}]).filter((e) => e.locationId !== item.locationId)
    } else {
      isPitchOnList = [item, ...isPitchOnList]
    }
    const WorkLocations = []
    isPitchOnList.map((item) => {
      item.cityName = item.cityName.replace(/市/, '')
      WorkLocations.push(item.addressSimple || item.address)
    })
    this.setState({
      isPitchOnList,
      WorkLocations,
      isChecAll: isPitchOnList.length === locationList.length
    })
  }

  prewClick = () => {
    const { navigation: { state: { params: { companyId, getData } } } } = this.props
    companyRightInfo({ headers: { companyId } }).then((data) => {
      const { isPitchOnList, WorkLocations } = this.state
      if (data.data.postAddress == -1 || isPitchOnList.length <= data.data.postAddress) {
        getData(isPitchOnList, WorkLocations)
      } else {
        this.setState({
          vipModal: true,
          vipModalText: `当前${data.data.member ? (data.data.memberLevel == 'vip1' ? '年度' : data.data.memberLevel == 'vip2' ? '月度' : data.data.memberLevel == 'vip3' ? '半年' : '') : '不是'}会员一次最多可选择${data.data.postAddress}个地点`,
          member: data.data.member
        })
      }
    })
  }

  jumpFn = ({ isDel, data = {} }) => {
    const { navigation: { state: { params: { companyId } } } } = this.props
    const item = {
      ...data,
      areaProvince: '',
      areaCity: data.cityName || '',
      addressArea: data.areaName || ''
    }
    this.props.navigation.navigate('BusinessAddress', { getCompanyWorkLocationList: this.getCompanyWorkLocationList, getData: this.getData, companyId, title: '添加地点', isDel, data: item })
  }

  delState = () => {
    this.setState({
      isDelState: !this.state.isDelState,
      isChecAll: false,
      isPitchOnList: [],
      WorkLocations: []
    })
  }

  selectAll = () => {
    this.setState({
      isPitchOnList: !this.state.isChecAll === true ? this.state.locationList : [],
      isChecAll: !this.state.isChecAll
    })
  }

  onDelete = () => {
    this.setState({
      visible: !this.state.visible
    })
  }

  deleteCompanyWorkLocation = () => {
    const { isPitchOnList } = this.state
    const { navigation: { state: { params: { userId } } } } = this.props
    if (isPitchOnList.length > 0) {
      const idlist = []
      isPitchOnList.map((item) => {
        const id = item.locationId
        idlist.push(id)
      })
      deleteCompanyWorkLocation({ params: { ids: idlist.join(','), userId } }).then(data => {
        this.setState({
          visible: false,
          isDelState: false,
          isPitchOnList: []
        })
        if (data.data) {
          this.getCompanyWorkLocationList()
          CommonToast('删除成功')
        } else {
          CommonToast('操作失败')
        }
      })
    } else {
      CommonToast('请选择删除地址')
    }
  }

  ModalFn = (modal) => {
    this.setState({
      vipModal: false,
      visible: false
    })
  }

  upgradeVip = () => {
    this.setState({
      vipModal: false
    })
    if (!this.state.member) {
      this.props.navigation.navigate('BMemberOpen')
    }
  }

  childRender() {
    const { locationList, isPitchOnList, isDelState, isChecAll, visible, vipModal, vipModalText, member } = this.state
    console.log(isPitchOnList, 'isPitchOnListisPitchOnListisPitchOnList')
    return (
      <View style={styles.container}>
        <Text style={styles.addSiteTopTitle}>工作地点</Text>
        <View style={styles.headerView}>
          <Text style={styles.addSiteTopText}>*仅限添加1个地址，会员可添加多个</Text>
          <CustomButton onPress={this.delState}>
            <CustomImage style={styles.pitchOnSize} source={isDelState ? require('src/imgC/part/yellow_del_icon.png') : require('src/imgC/part/del_icon.png')} />
          </CustomButton>
        </View>
        <ScrollView contentContainerStyle={styles.scrollView}>
          {
            (locationList || []).map((item, index) => {
              const isPitchOn = isPitchOnList.filter((e) => e.locationId === item.locationId)
              return (
                <CustomButton key={index} style={styles.itemView}>
                  {!!isDelState && <CustomButton onPress={this.isPitchOn} params={{ item }} style={styles.itemleftIcon}>
                    {(isPitchOn || []).length > 0 && <CustomImage style={styles.CustomImage} source={require('src/imgC/login/onelogin_check.png')} />}
                  </CustomButton>}
                  <CustomButton onPress={this.isPitchOn} params={{ item }} style={styles.itemRightView}>
                    <CustomImage style={styles.temRightItem} source={(isPitchOn || []).length > 0 ? require('src/imgC/part/yellow-location.png') : require('src/imgC/part/location.png')} />
                    <Text ellipsizeMode='tail' numberOfLines={1} style={[styles.itemRightText, (isPitchOn || []).length > 0 && styles.yellowItemRightText]}>
                      {item.addressSimple || item.address || ''}
                    </Text>
                  </CustomButton>
                </CustomButton>)
            })
          }
        </ScrollView>
        <View style={styles.customBoxShadowView}>
          <CustomBoxShadow style={styles.customBoxShadow}>
            {!isDelState && <CustomButton onPress={this.jumpFn} params={{ isDel: false }} style={styles.button}>
              <CustomImage source={require('src/imgC/userinfo/add_black.png')} />
              <Text style={styles.buttonText}>添加地点</Text>
            </CustomButton>}
            {!!isDelState && <CheckDeleteView
              style={styles.checkDeleteView}
              checked={isChecAll}
              highlight={isPitchOnList.length > 0}
              onCheckedPress={this.selectAll}
              onDeletePress={this.onDelete} />}
          </CustomBoxShadow>
        </View>
        <CustomModalAnimatable onPress={this.ModalFn} params={{ visible: false }} visible={visible}>
          <View style={styles.modalView}>
            <Text style={styles.title}>温馨提示</Text>
            <Text style={styles.text}>{`确定删除选中的${(isPitchOnList || []).length || 0}个地点吗？`}</Text>
            <CustomButton
              onPress={this.ModalFn}
              params={{ visible: false }}
              style={styles.noButton}
            >
              <Text style={styles.noButtonText}>取消</Text>
            </CustomButton>
            <CustomButton
              onPress={this.deleteCompanyWorkLocation}
              style={styles.yesButton}
            >
              <Text style={styles.yesButtonText}>确定</Text>
            </CustomButton>
          </View>
        </CustomModalAnimatable>
        <CustomModalAnimatable onPress={this.ModalFn} params={{ vipModal: false }} visible={vipModal}>
          <View style={styles.modalView}>
            <Text style={styles.title}>温馨提示</Text>
            <Text style={styles.text}>{vipModalText}</Text>
            {!member && <CustomButton
              onPress={this.ModalFn}
              params={{ vipModal: false }}
              style={styles.noButton}
            >
              <Text style={styles.noButtonText}>修改地址</Text>
            </CustomButton>}
            <CustomButton
              onPress={this.upgradeVip}
              style={styles.yesButton}
            >
              <Text style={styles.yesButtonText}>{member ? '确定' : '升级会员'}</Text>
            </CustomButton>
          </View>
        </CustomModalAnimatable>
      </View>
    )
  }

  renderNavigationBarChild = () => {
    let { isDelState } = this.state
    return (
      <CustomButton style={!isDelState && [styles.naviBtnBG]} onPress={this.prewClick}>
        {!isDelState && <Text>保存</Text>}
      </CustomButton>
    )
  }
}

export default AddSite
